package com.project.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.project.dao.BookInfoDAO;
import com.project.dao.GenericDAO;
import com.project.dto.CountBookType;
import com.project.entity.BookInfo;
import com.project.entity.ReaderInfo;
import com.project.service.BookInfoService;

@Service("bookInfoService")
public class BookInfoServiceImpl extends GenericServiceImpl<BookInfo, Integer>
		implements BookInfoService {
	private BookInfoDAO bookInfoDAO;

	@Resource(name = "bookInfoDAO")
	@Override
	public void setGenericDAO(GenericDAO<BookInfo, Integer> genericDAO) {
		this.genericDAO = genericDAO;
		this.bookInfoDAO = (BookInfoDAO) genericDAO;
	}

	@Override
	public List<BookInfo> getBookList(Object object) {
		return bookInfoDAO.getBookList(object);
	}

	@Override
	public BookInfo get(String name) {
		return bookInfoDAO.get(name);
	}

	@Override
	public List<Integer> availableQuan(String queryParams) {
		return bookInfoDAO.availableQuan(queryParams);
	}

	@Override
	public BookInfo verifyBookInfo(Object... objects) {
		return bookInfoDAO.verifyBookInfo(objects);
	}

	@Override
	public List<CountBookType> countBookType() {
		return bookInfoDAO.countBookType();
	}

	@Override
	public List<BookInfo> search(String bookName, Integer btypeId,
			Integer pageNow, Integer pageSize) {
		List<BookInfo> list = null;
		List<BookInfo> newList = new ArrayList<BookInfo>();
		Integer offset = (pageNow - 1) * pageSize;

		if (StringUtils.isBlank(bookName) && btypeId == 0) {
			list = bookInfoDAO.findByPage(offset, pageSize);
		} else if (StringUtils.isBlank(bookName) && btypeId > 0) {
			list = bookInfoDAO.searchByType(btypeId, offset, pageSize);
		} else if (StringUtils.isNotBlank(bookName) && btypeId == 0) {
			list = bookInfoDAO.searchByName(bookName, offset, pageSize);
		} else if (StringUtils.isNotBlank(bookName) && btypeId > 0) {
			list = bookInfoDAO.searchByNameAndType(bookName, btypeId, offset,
					pageSize);
		}

		if (list.size() > 0) {
			for (BookInfo bookInfo : list) {
				ReaderInfo entryReader = new ReaderInfo();
				ReaderInfo deleteReader = new ReaderInfo();

				bookInfo.getBookType().getId();
				if (bookInfo.getEntryReader() != null) {
					entryReader.setName(bookInfo.getEntryReader().getName());
					bookInfo.setEntryReader(entryReader);
				}
				if (bookInfo.getDeleteReader() != null) {
					deleteReader.setName(bookInfo.getDeleteReader().getName());
					bookInfo.setDeleteReader(deleteReader);
				}

				newList.add(bookInfo);
			}
		}

		return newList;
	}

	@Override
	public Integer totalCount(String bookName, Integer btypeId) {
		return bookInfoDAO.totalCount(bookName, btypeId);
	}

}
